<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { get_products } from '@/api/products';

// 创建一个ref来引用图表容器
const chartRef = ref(null);

// 定义响应式数据
const date = reactive({
  isFirst: true,
  data: [],
  Products: [],
  loading: false,
  key: "",
  details_key: "",
  details_key_id: "",
  pages: {
    page: 1,
    limit: 10,
    total: 0,
  },
  time1: "",
  time2: ""
});

interface Product {
  id: string;
  name: string;
  price: number;
  datetime: string;
  img: string;
  expalain: string;
  list: number;
  enddatetime: string;
  startdatetime: string;
  discountprice: number;
  salesvolume: number;
}

const productsData = ref<Product[]>([]);

const fetchTypes = async () => {
  date.loading = true;
  try {
    const res2 = await get_products({
      key: "",
    });
    if (res2.code === 0) {
      productsData.value = res2.data.data;
      initChart(); // 数据获取后初始化图表
    }
  } catch (error) {
    console.error('获取类型失败:', error);
    ElMessage.error('获取类型失败');
  } finally {
    date.loading = false;
  }
};

fetchTypes();

// 初始化图表
const initChart = () => {
  // 获取DOM元素
  const chartDom = chartRef.value;
  if (!chartDom) return;

  // 初始化ECharts实例
  const myChart = echarts.init(chartDom);

  // 确保数据已经加载完成
  if (productsData.value.length === 0) {
    setTimeout(() => {
      initChart();
    }, 100); // 延迟一段时间确保数据加载完成
    return;
  }

  // 生成并排序数据
  const initialData = generateDataFromProducts(productsData.value).sort((a, b) => a.value - b.value);

  // 配置项和数据
  const option = {
    title: {
      text: '静态柱状图'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      data: initialData.map(item => item.name)
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: initialData.map(item => item.value)
    }]
  };

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
};

// 根据productsData生成图表所需的数据格式
function generateDataFromProducts(products: Product[]) {
  return products.map(product => ({
    name: product.name,
    value: product.salesvolume
  }));
}
</script>

<style scoped>
/* 添加一些样式 */
#main {
  width: 100%;
  height: 400px;
}
</style>
